package com.yeziji.security.component;

import cn.hutool.json.JSONUtil;
import com.yeziji.common.CommonResult;
import com.yeziji.common.context.OnlineContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 无权限访问
 *
 * @author hwy
 * @since 2023/11/12 20:27
 **/
@Slf4j
public class RequestAccessDeniedHandler implements AccessDeniedHandler {
    @Override
    public void handle(HttpServletRequest request,
                       HttpServletResponse response,
                       AccessDeniedException accessDeniedException) throws IOException {
        if (!OnlineContext.isHasSession()) {
            log.info("{} 无权访问: {} -- {}", OnlineContext.getIp(), request.getRequestURI(), accessDeniedException.getMessage());
        } else {
            log.info("{} 无权访问: {} -- {}", OnlineContext.getUserId(), request.getRequestURI(), accessDeniedException.getMessage());
        }

        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Cache-Control", "no-cache");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        response.getWriter().println(JSONUtil.parse(CommonResult.forbidden()));
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        response.getWriter().flush();
    }
}
